import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from '@/stores/userStore';

const routes = [
  { 
    path: '/',
    name: 'Index',
    title: '首页',
    component: () => import('@/views/index.vue'), // 更新路径
    meta: { requiresAuth: false } // 明确添加meta信息
  },
  { 
    path: '/mall',
    name: 'Mall', 
    title: '商场',
    component: () => import('@/views/mall/index.vue'), // 更新路径
    meta: { requiresAuth: false } // 示例：需要登录的页面
  },
  { 
    path: '/user/login',
    name: 'Login',
    title: '登录',
    component: () => import('@/views/login/index.vue'), // 更新路径
    meta: { guestOnly: true } // 仅未登录用户可访问
  },
  { 
    path: '/user/register',
    name: 'Register',
    title: '注册',
    component: () => import('@/views/register/index.vue'), // 更新路径
    meta: { guestOnly: true }
  },
  { 
    path: '/user/person',
    name: 'Person',
    title: '个人中心',
    component: () => import('@/views/person/index.vue'), // 更新路径
    meta: { requiresAuth: true }
  },
  { 
    path: '/user',
    name: 'User',
    title: '用户管理',
    component: () => import('@/views/user/index.vue'), // 更新路径
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 更好的base URL处理
  routes
});

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  
  // 初始化用户状态（确保异步操作完成）
  await userStore.initialize();
  
  // 登录状态检查
  const isLoggedIn = userStore.isLoggedIn;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const guestOnly = to.matched.some(record => record.meta.guestOnly);

  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录 → 跳转登录页
    next({ 
      name: 'Login',
      query: { redirect: to.fullPath } // 保存目标路径以便登录后跳转
    });
  } else if (guestOnly && isLoggedIn) {
    // 已登录但访问游客页面 → 跳转首页
    next({ name: 'Index' });
  } else {
    // 正常放行
    next();
  }
});

export default router;